package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.learning.model.dto.CourseRecordDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.learning.agent.CoursePubIndexApiAgent;
import com.xuecheng.learning.agent.MediaApiAgent;
import com.xuecheng.learning.convert.CourseRecordConvert;
import com.xuecheng.learning.entity.CourseRecord;
import com.xuecheng.learning.mapper.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    @Autowired
    private CoursePubIndexApiAgent indexApiAgent;

    @Autowired
    private MediaApiAgent mediaApiAgent;

    /*
    * 业务分析：
    *   1.判断关键数据
    *   2.根据条件查询用户的学习记录
    *   3.返回学习记录数据
    *       如果有数据返回
    *       如果没有返回空数据
    * */
    public CourseRecordDTO getRecordByCoursePubId(Long coursePubId, String username) {

        // 1.判断关键数据
        if (ObjectUtils.isEmpty(coursePubId)||
                StringUtil.isBlank(username)
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }


        //  2.根据条件查询用户的学习记录(一个人对一门课只有一个学习记录)
        LambdaQueryWrapper<CourseRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseRecord::getCoursePubId, coursePubId);
        queryWrapper.eq(CourseRecord::getUserName, username);

        CourseRecord courseRecord = this.getOne(queryWrapper);



        //  3.返回学习记录数据
        CourseRecordDTO courseRecordDTO = null;
        if (ObjectUtils.isEmpty(courseRecord)) {
        //      如果没有返回空数据
            courseRecordDTO = new CourseRecordDTO();
        } else {
        //      如果有数据返回
            courseRecordDTO = CourseRecordConvert.INSTANCE.entity2dto(courseRecord);
        }
        return courseRecordDTO;
    }




}
